//导入路由 elemen-ui axios store 正则校验函数
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from '@/http'
import store from './store'
import { nameTest, pwdTest } from './utils/reg.js'

//响应拦截器
axios.interceptors.response.use(function(response) {
	let data = response.data;
	if (data) {
		if (data.token) {
			store.commit('setToken', data.token);
		}
		if (data.user && data.user.id) {
			store.commit('setUid', data.user.id);
		}
	}
	return response;
})

//请求拦截器 使用请求拦截器为每个请求添加 token
axios.interceptors.request.use(function(request) {
	//获取 id 跟 token
	let id = store.state.uid;
	let token = store.state.token;

	if (token != '' && id != '') {
		request.headers.authorization = token;
		if (request.params) request.params.id = id;
		else request.params = {id};
	}
	return request;
})

//路由守卫，配置前置操作
router.beforeEach((to, from, next) => {
	if (to.path == '/login') next();
	else {
		axios.get('/users/backend/list').then(({data: {code}}) => {
				if (code != 1) router.push('/login');
				else next();
			})
	}
})

//将 axios 正则校验函数  store 放到原型上
Vue.prototype.$http = axios
Vue.prototype.$store = store
Vue.prototype.$nameTest = nameTest;
Vue.prototype.$pwdTest = pwdTest;

//使用 element-ui
Vue.use(ElementUI);
new Vue({
	render: h => h(App),
	router,  //将路由配置到 vue 实例中
}).$mount('#app')
